import os
import uuid
from django.conf import settings
from django.core.files.storage import default_storage
from PIL import Image as PILImage
from io import BytesIO

# 导入MinioClient
from tools.minio_client import minio_client

def validate_image(image):
    """验证图片"""
    # 检查文件大小
    if image.size > settings.MAX_IMAGE_SIZE:
        return False, f'图片大小不能超过{settings.MAX_IMAGE_SIZE // (1024 * 1024)}MB'
    
    # 检查文件类型
    if image.content_type not in settings.ALLOWED_IMAGE_TYPES:
        return False, '只支持JPEG、PNG、GIF格式的图片'
    
    return True, None


def compress_image(image, max_size=(1024, 1024)):
    """压缩图片"""
    img = PILImage.open(image)
    
    # 转换RGBA模式为RGB（JPEG不支持RGBA）
    if img.mode in ('RGBA', 'LA', 'P'):
        img = img.convert('RGB')
    
    # 调整图片大小
    img.thumbnail(max_size, PILImage.LANCZOS)
    
    # 保存到内存
    img_io = BytesIO()
    img.save(img_io, format='JPEG', quality=85, optimize=True)
    img_io.seek(0)
    
    # 生成新的文件名
    filename = f"{uuid.uuid4().hex}.jpg"
    
    return img_io, filename


def upload_to_minio(image, user_id, image_type):
    """上传图片到MinIO"""
    try:
        # 验证图片
        is_valid, error = validate_image(image)
        if not is_valid:
            raise ValueError(error)
        
        # 压缩图片
        img_io, filename = compress_image(image)
        
        # 生成保存路径
        path = f'images/{user_id}/{image_type}/{filename}'
        
        # 上传文件到MinIO
        image_data = img_io.getvalue()
        minio_client.upload_bytes(path, image_data, content_type='image/jpeg')
        
        # 返回访问URL
        url = minio_client.presigned_get_url(path)
        return url
        
    except Exception as e:
        raise RuntimeError(f'上传到MinIO失败: {str(e)}')


def upload_to_local(image, user_id, image_type):
    """上传图片到本地"""
    # 验证图片
    is_valid, error = validate_image(image)
    if not is_valid:
        raise ValueError(error)
    
    # 压缩图片
    img_io, filename = compress_image(image)
    
    # 生成保存路径
    path = f'images/{user_id}/{image_type}/{filename}'
    
    # 保存文件
    file_path = default_storage.save(path, img_io)
    
    return file_path


def upload_to_oss(image, user_id, image_type):
    """上传图片到阿里云OSS"""
    try:
        import oss2
        
        # 验证图片
        is_valid, error = validate_image(image)
        if not is_valid:
            raise ValueError(error)
        
        # 压缩图片
        img_io, filename = compress_image(image)
        
        # 初始化OSS客户端
        auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET)
        bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME)
        
        # 生成保存路径
        path = f'images/{user_id}/{image_type}/{filename}'
        
        # 上传文件
        bucket.put_object(path, img_io)
        
        # 返回访问URL
        url = f'https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/{path}'
        return url
        
    except ImportError:
        raise ImportError('请安装oss2库: pip install oss2')


def upload_to_cos(image, user_id, image_type):
    """上传图片到腾讯云COS"""
    try:
        import qcloud_cos
        
        # 验证图片
        is_valid, error = validate_image(image)
        if not is_valid:
            raise ValueError(error)
        
        # 压缩图片
        img_io, filename = compress_image(image)
        
        # 初始化COS客户端
        config = qcloud_cos.CosConfig(
            Region=settings.COS_REGION,
            SecretId=settings.COS_SECRET_ID,
            SecretKey=settings.COS_SECRET_KEY
        )
        client = qcloud_cos.CosS3Client(config)
        
        # 生成保存路径
        path = f'images/{user_id}/{image_type}/{filename}'
        
        # 上传文件
        response = client.put_object(
            Bucket=settings.COS_BUCKET_NAME,
            Body=img_io,
            Key=path,
            StorageClass='STANDARD'
        )
        
        # 返回访问URL
        url = f'https://{settings.COS_BUCKET_NAME}.cos.{settings.COS_REGION}.myqcloud.com/{path}'
        return url
        
    except ImportError:
        raise ImportError('请安装qcloud_cos库: pip install cos-python-sdk-v5')